﻿using Infrastructure.Excel;
using Infrastructure.Operator;
using Infrastructure.Web;
using MyData.ApiDto;
using MyData.Dto;
using MyData.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyWeb.Controllers
{
    public class VisitorController : BaseController
    {
        private static string imgPath = @"/Attach/Company/";
        // GET: Visitor
        public ActionResult Index()
        {
            if (OperatorProvider.Provider.GetCurrent().DepartId.HasValue)
            {
                ViewBag.Departs = departApp.GetList().Where(c => c.Id == OperatorProvider.Provider.GetCurrent().DepartId.Value).ToList();
            }
            else
            {
                ViewBag.Departs = departApp.GetList();
            }
            return View();
        }
        public ActionResult VisitorRecords()
        {
            ViewBag.Departs = departApp.GetList();
            ViewBag.Mobiles = mobileApp.GetMobiles();
            return View();
        }
        public ActionResult WXVisitor()
        {
            // ViewBag.DepartsView = getRaw();
            ViewBag.MeetName = MeetApp.GetMeetDto(null)?.MeetName;
            return View();
        }
        public string getRaw()
        {
            return JsonConvert.SerializeObject(departApp.GetList());
        }
        public ActionResult CompanyIndex(string meetId)
        {
            ViewBag.MeetId = meetId;
            return View();
        }

        public ActionResult GetCompamyUsers(QueryListModel query, string Company,string MeetId)
        {
            var resultList = visitorApp.GetCompanyUser(query, Company,MeetId);
            return Json(resultList, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="query"></param>
        /// <param name="DepartId"></param>
        /// <param name="Company"></param>
        /// <returns></returns>
        public ActionResult GetVisitor(QueryListModel query, Guid DepartId, string Company)
        {
            if (OperatorProvider.Provider.GetCurrent().DepartId.HasValue)
            {
                DepartId = OperatorProvider.Provider.GetCurrent().DepartId.Value;
            }
            var resultList = visitorApp.GetVisitor(query, DepartId, Company);
            return Json(resultList, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CheckView(string Id)
        {
            ViewBag.DepartsView = departApp.GetList();
            if (!String.IsNullOrEmpty(Id))
            {
                var dto = visitorApp.CheckVisitor(Guid.Parse(Id));
                return View(dto);
            }
            return View(new VisitorDto());

        }
        [HttpPost]
        public JsonResult VisitorDelete(Guid Id)
        {
            return base.Try(() =>
            {
                visitorApp.VisitorDelete(Id);
            }
            );
        }
        [HttpPost]
        public JsonResult SaveVisitor(Visitor visitor)
        {
            return base.Try(() =>
            {
                visitorApp.Save(visitor);
            });
        }
        [HttpPost]
        public JsonResult SaveCompany(MeetUser meetUser)
        {
            return base.Try(() =>
            {
                bool result = visitorApp.SaveMeet(meetUser);
                if (result == false)
                {
                    throw new KnownException("添加失败或重复添加");
                }
            });
        }
        [HttpPost]
        public JsonResult CompanyDelete(Guid Id)
        {
            return base.Try(() =>
            {
                visitorApp.CompanyDelete(Id);
            }
            );
        }
        public ActionResult CheckCompanyView(string Id)
        {

            if (!String.IsNullOrEmpty(Id))
            {
                var dto = visitorApp.CheckCompany(Guid.Parse(Id));
                return View(dto);
            }
            return View(new MeetUserDto());

        }
        [HttpPost]
        public JsonResult SaveHeadImg(string base64,int type)
        {
            var result = new AjaxResult<String>();
            return base.Try<String>(() =>
            {
                try
                {
                    string fullPath = Server.MapPath(imgPath) + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                    if (!Directory.Exists(fullPath))
                    {
                        Directory.CreateDirectory(fullPath);
                    }
                    string fileExtension = ".jpg";
                    string saveName = Guid.NewGuid() + fileExtension;
                    var array = base64.Split(',');
                    Bitmap bitmap = ConvertStringToBitmap(array[1]);
                    if (type == 1)
                    {
                        bitmap.RotateFlip(RotateFlipType.Rotate90FlipX);
                    }

                    bitmap.Save(fullPath + saveName);
                    //if (FSDK.FSDKE_OK != FSDK.ActivateLibrary("gyYgVWQTSzjiuGB/hH8dKgg0QrrIuhoHdfUCzD9rY+vru3WRZsaezTX6YWj9osdI/cmxY1NSdLkyWuugMPCxUG7/xNLegHLeaUpzVyKpDkaWL8tJIUsIL7xv9bhmgifPbAyTDuxF3VGxXmHkv/L/MStf9kdXV/A1vVvT93QC4vQ="))
                    //{
                    //    throw new KnownException("人脸引擎失败");
                    //}

                    //FSDK.InitializeLibrary();
                    //FSDKCam.InitializeCapturing();

                    //FSDK.CImage image = new FSDK.CImage(fullPath + saveName);
                    //TFacePosition facePosition = image.DetectFace();
                    //if (facePosition.w == 0)
                    //{
                    //    System.IO.File.Delete(fullPath + saveName);
                    //    throw new KnownException("未检测到人脸");
                    //}
                    result.data = imgPath + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + saveName;
                }
                catch (Exception ex)
                {
                    result.data = ex.Message;
                }
              
            }, result);
        }
      
        Bitmap ConvertStringToBitmap(string base64string)
        {
            byte[] bt = Convert.FromBase64String(base64string);
            MemoryStream h_stream = new MemoryStream(bt);
            Bitmap h_bitmap = new Bitmap(h_stream);
            return h_bitmap;
        }
        /// <summary>
        /// 附件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadProduct(string fileNamePath, string toFilePath)
        {
            var result = new AjaxResult<String>();
            return base.Try<String>(() =>
            {
                var file = HttpContext.Request.Files[0];
                string fileName = file.FileName;
                string ext = Path.GetExtension(file.FileName).ToLower();
                string name = Guid.NewGuid().ToString().ToLower() + ext;
                string path = $@"{imgPath}/";
                string fullPath = Server.MapPath(path);
                if (!Directory.Exists(fullPath))//创建文件夹
                    Directory.CreateDirectory(fullPath);
                file.SaveAs(fullPath + name);
                //if (FSDK.FSDKE_OK != FSDK.ActivateLibrary("gyYgVWQTSzjiuGB/hH8dKgg0QrrIuhoHdfUCzD9rY+vru3WRZsaezTX6YWj9osdI/cmxY1NSdLkyWuugMPCxUG7/xNLegHLeaUpzVyKpDkaWL8tJIUsIL7xv9bhmgifPbAyTDuxF3VGxXmHkv/L/MStf9kdXV/A1vVvT93QC4vQ="))
                //{
                //    throw new KnownException("人脸引擎失败");
                //}

                //FSDK.InitializeLibrary();
                //FSDKCam.InitializeCapturing();

                //FSDK.CImage image = new FSDK.CImage(fullPath + name);
                //TFacePosition facePosition = image.DetectFace();
                //if (facePosition.w == 0)
                //{
                //    System.IO.File.Delete(fullPath + name);
                //    throw new KnownException("未检测到人脸");
                //}
                result.data = path + name;
            }, result);
        }

        public FileResult ExcelImport()
        {
            List<MeetUserDto> checkInDtos = Session["Company"] as List<MeetUserDto>;
            if (checkInDtos == null) checkInDtos = new List<MeetUserDto>();
            var result = checkInDtos.OrderByDescending(c=>c.MeetName).ThenByDescending(c=>c.CompanyName).Select(c => new MeetUserExcel()
            {
                MeetName = c.MeetName,
                CompanyName = c.CompanyName,
                Position = c.Position,
                UserName = c.UserName,
                PhoneNum = c.PhoneNum
            }).ToList();
            string filename = $"~/Export/{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
            filename = Server.MapPath(filename);
            EpplusHelper.SaveToExcel(result, filename,new string[] { "会议名称","单位名称", "职位","姓名","手机号"});
            return File(filename, "application/octet-stream", $"{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls");
        }


        public ActionResult GetVisitorRecord(QueryListModel query, string NickName, Guid MobileId, string StartDate, string EndDate)
        {
            DateTime startDate = DateTime.Parse(StartDate).Date;
            DateTime endDate = DateTime.Parse(EndDate).Date.AddDays(1);
            var result = AccessRecordApp.GetVisitorRecord(query, NickName, MobileId,startDate,endDate);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult VisitorConfirm(Guid Id)
        {
            return base.Try(()=> {

                visitorApp.VisitorConfirm(Id);
            });
        }
    }
}